package io.qar.mq.producer;

import com.alibaba.fastjson.JSONObject;
import io.qar.mq.entity.OrdersEntity;
import io.qar.mq.service.TransactionLogService;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
/**
 * @program: qar-cloud
 * @description:
 * @author: yyyyjinying
 * @create: 2023-10-18 14:51
 **/
@RocketMQTransactionListener
public class TransactionMsgListener implements RocketMQLocalTransactionListener {
    @Autowired
    private TransactionLogService transactionLogService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {

        String body = new String((byte[]) msg.getPayload());
        OrdersEntity orders = JSONObject.parseObject(body, OrdersEntity.class);
        String transactionId = msg.getHeaders().getId().toString();
        RocketMQLocalTransactionState state;
        try {
            transactionLogService.createOrder(orders, transactionId);
            state = RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            state = RocketMQLocalTransactionState.ROLLBACK;
        }
        return state;
    }

    // 消息回查
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        String transactionId = msg.getHeaders().getId().toString();
        if (transactionLogService.hasTransctionId(transactionId)) {
            return RocketMQLocalTransactionState.COMMIT;
        }
        return RocketMQLocalTransactionState.UNKNOWN;
    }
}
